package account

import (
	"context"
	"time"

	"gozero/login/internal/biz"
	"gozero/login/internal/model"
	"gozero/login/internal/svc"
	"gozero/login/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterLogic) Register(req *types.RegisterReq) (resp *types.RegisterResp, err error) {
	// 检查用户是否存在
	userModel := model.NewUserModel(l.svcCtx.Mysql)
	u, err := userModel.FindOneByUsername(l.ctx, req.Username)
	if err != nil && err != sqlx.ErrNotFound {
		l.Logger.Error(err)
		return nil, biz.DBError
	}
	if u != nil {
		return nil, biz.AlreadyRegisted
	}
	// 创建用户
	userModel.Insert(l.ctx, &model.User{
		Username:      req.Username,
		Password:      req.Password,
		RegisterTime:  time.Now(),
		LastLoginTime: time.Now(),
	})
	return &types.RegisterResp{Status: "ok"}, nil
}
